//
//  CHAccount.swift
//  status
//
//  Created by 彳亍 on 2017/3/23.
//  Copyright © 2017年 彳亍. All rights reserved.
//

import UIKit
import YYModel

class CHAccount: NSObject {

    /// 用户授权的唯一票据
    var access_token:String?
    /// access_token的生命周期，单位是秒数
    var expires_in:TimeInterval = 0 {
        didSet{
            expires_date = Date(timeIntervalSinceNow: expires_in)
        }
    }
    /// 授权用户的UID
    var uid:String?
    
    /// 用户昵称
    var screen_name:String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large:String?
    
    var expires_date:Date?
    
    
    /// 保存账户信息
    func saveAccount() {
        let userDefault = UserDefaults.standard
        userDefault.set(access_token, forKey: "access_token")
        userDefault.set(expires_in, forKey: "expires_in")
        userDefault.set(expires_date, forKey: "expires_date")
        userDefault.set(uid, forKey: "uid")
        userDefault.set(screen_name, forKey: "screen_name")
        userDefault.set(avatar_large, forKey: "avatar_large")
    }
    
    /// 构造方法
    override init() {
        super.init()
        
        let userDefault = UserDefaults.standard
        
        // 获取过期日期
        expires_date = userDefault.object(forKey: "expires_date") as? Date
        
        if expires_date?.compare(Date()) != ComparisonResult.orderedDescending {
            // 账号过期
            return
        }
        
        expires_in = userDefault.double(forKey: "expires_in")
        access_token = userDefault.object(forKey: "access_token") as? String
        uid = userDefault.object(forKey: "uid") as? String
        screen_name = userDefault.object(forKey: "screen_name") as? String
        avatar_large = userDefault.object(forKey: "avatar_large") as? String
        

    }
    
    
    /// 重写 description
    override var description: String {
        return yy_modelDescription()
    }
    
}
